<?php
/**
* File holding the context class
*
* @author       Fabrice Douteaud <clearbudget@douteaud.com>
* @package      framework
* @access       public
*/

/***********************************************************************

  Copyright (C) 2008  Fabrice douteaud (clearbudget@douteaud.com)

    This file is part of ClearBudget.

    ClearBudget is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    ClearBudget is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with ClearBudget.  If not, see <http://www.gnu.org/licenses/>.


************************************************************************/

/**
* Class handling the context of each request. It maintains the context of the request by
* keeping all related variables to their original values and by letting other classes and files
* accessing them
* 
* @author       Fabrice Douteaud <clearbudget@douteaud.com>
* @package      framework
* @access       public
*/
class class_context {
	/**
	* @var object Hold the instance of the current class
	* @access private
	* @static	
	*/
  private static $_instance = null;
  /**
	* @var string the user prefered language
	* @access public
	* @static	
	*/
  public static $language = null;
  /**
	* @var string the user prefered currency
	* @access public
	* @static	
	*/
  public static $currency = null;
  /**
	* @var string the month to select transaction from
	* @access public
	* @static	
	*/
  public static $limitMonth = null;
  /**
	* @var string the user requested action
	* @access public
	* @static	
	*/
  public static $action = null;
  /**
	* @var string the next action to be processed (usually set in the actions)
	* @access public
	* @static	
	*/
  public static $nextAction = null;
  /**
	* @var string the requested snippets (usually equals to $action)
	* @access public
	* @static	
	*/
  public static $snippet = null;
  /**
	* @var boolean a flag to set if the request is in AJAX mode
	* @access public
	* @static	
	*/
  public static $ajax = null;

  /**
	* Gets the default language from the user-agent 
	*	
	* Reads the HTTP headers from the request for the HTTP_ACCEPT_LANGUAGE tag.
	* If found, it return the first language.
	*     		
	* @return mixed the language as a string is any OR boolean false
	* @access public
	* @static	
	*/
  public static function getUserAgentLanguage() {
    // if the user agent did not send anything, return false
    if (!isset($_SERVER["HTTP_ACCEPT_LANGUAGE"])) return false;

    // get all languages
    $langs=explode(",",$_SERVER["HTTP_ACCEPT_LANGUAGE"]);
    
    // get the first language in the list
    $lang=strtolower(substr($langs[0],0,2));
    
    // TODO : loop through all and sort them looking at the q flag
    // top q flag should be the language taken
    /* 
    //start going through each one
    foreach ($langs as $value) {
      //select only the first two letters
      $lang=substr($value,0,2);
      }
    */
    class_debug::addMsg(__FILE__, 'user agent language is '.$lang, DEBUGDEBUG);
    return $lang;
    }
  
  /**
	* Sets the max number of month to look transaction from 
	*	
	* The max number of month to look up data for is used to avoid loading all the transactions from the DB.
	* This value is kept in a cookie. If no cookie is present, then a default value is applied.	
	*     		
	* @return void
	* @access private
	* @static	
	*/
  private static function getlimitMonth() {
    // if the cookie exist, we get the value from it
    if(isset($_COOKIE['limitMonth']) && $_COOKIE['limitMonth'] != null) {
      self::$limitMonth = $_COOKIE['limitMonth'];
      }
    else {    
      // if not, we get the default
      $report = class_report::getInstance();
      self::$limitMonth = $report->getlimitMonth(DEFAULTMONTHRANGE);
      // set the cookie to avoid round-trip to the DB 
      setcookie("limitMonth", self::$limitMonth);
      }
    }
  
  /**
	* Initialize the context object by loading all the different values 
	*	
	*	
	* @return void
	* @access private
	* @static	
	*/
  private static function init() {
    // see if any action is needed (not only display of information)
    isset($_REQUEST['action'])?self::$action = $_REQUEST['action']:self::$action = 'home';
    
    // get the AJAX parameter telling us if it is an ajax call or not
    isset($_REQUEST['ajax'])?self::$ajax = $_REQUEST['ajax']:self::$ajax = false;
    
    // get the Language from the settings object
    self::$language = class_settings::$language;
    
    // get the Currency from the settings object
    self::$currency = class_settings::$currency;
    
    // if user did not select a prefered language, set the language to the prefered user agent language
    if(self::$language == null || self::$language == '') {
      // set the context var
      self::$language = self::getUserAgentLanguage();
      // set the user preference
      //class_settings::setLanguage(self::$language);
      }
    
    // get the date range
    self::getlimitMonth();
    
    // we can set extra parameter in the action parameter as _param=value
    // this is used mainly to navigate to categories from summary tables
    $extra = explode('_', self::$action);
    if($extra[0] != self::$action) { // we found the _
      foreach($extra as $key) { // for each param
        $tmp = explode('=', $key); // explode with '='
        if($tmp[0] != $key) {
          $_GET[$tmp[0]] = $tmp[1]; // set the $_GET array with this extra param as it would come from the GET
          class_debug::addMsg(__FILE__, 'extra['.$tmp[0].']='.$tmp[1], DEBUGDEBUG);
          }
        }
      // cleanup the snippet var now
      self::$action = $extra[0];
      }
    
    // by default the snippet = the action
    self::$snippet = self::$action;
    
    class_debug::addMsg(__FILE__, 'action is "'.class_context::$action.'"', DEBUGDEBUG);
    class_debug::addMsg(__FILE__, 'language is "'.class_context::$language.'"', DEBUGDEBUG);
    class_debug::addMsg(__FILE__, 'limitMonth is "'.class_context::$limitMonth.'"', DEBUGDEBUG);
    }
  
  /**
	* Get the login status of the current user
	*	
	* Reads the login cookie in order to determine the user login status	
	*	
	* @return boolean a flag set to true or false depending on the login status
	* @access public
	* @static	
	*/
  public static function isUserLoggedIn() {
    if(isset($_COOKIE['user']) && $_COOKIE['user'] != null) {
      $userCookie = $_COOKIE['user'];      
      return true;
      }
    return false;
    }

  /**
	* Provide an instance of the current class 
	*	
	* Implementation of the singleton pattern
	*   		
	* @return object An instance of this class
	* @access public
	* @static	
	*/  
  public static function getInstance() {
    if(is_null(self::$_instance)) {
      self::$_instance = new self();
      }
    return self::$_instance;
    } // getInstance()

  /**
	* class constructor 
	*	
	* access to this class is private as to implement the singleton pattern
	*   	
	* @return void
	* @access private	
	*/
  private function __construct() {    
    // initialize the object
    self::init();
    } // __construct()
  }
?>